/**
 * @file main.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2024-07-21
 *
 * @copyright Copyright (c) 2024
 *
 * 本工程的目的时通过摄像头发送过来信息控制云台来追踪小球
 *
 */
#include "main.h"

#ifdef DEBUG
void __error__(char *pcFilename, uint32_t ui32Line)
{
}
#endif

keyParameter key; // 按键状态获取


_trace getTraceval;
_obtain Obtain;
_ctrl Ctrl={
    .Servos_x=80,
    .Servos_y=145
};

/**  结 束  **/

void Key_Proc(void)
{
    if (Tim_Total_Flag != 1)
        return;
    Tim_Total_Flag = 0;
    Key_EmShak(&key);
    if(key.down==Button_Down)
    {
        if (++Ctrl.Servos_y > 270)
            Ctrl.Servos_y = 270;
    }
    if (key.down == Button_Up)
    {
        if (--Ctrl.Servos_y < 100)
            Ctrl.Servos_y = 100;
    }
    if (key.down == Button_Left)
    {
        if (++Ctrl.Servos_x > 180)
            Ctrl.Servos_x = 180;
    }
    if (key.down == Button_Right)
    {
        if (--Ctrl.Servos_x > 180)
            Ctrl.Servos_x = 0;
    }
}

void Show_Proc(void)
{
    if (Tim_Total_Flag != 2)
        return;
    Tim_Total_Flag = 0;

//    OLED_DisPlay(1, "Servos_x:%d  ", Ctrl.Servos_x);
//    OLED_DisPlay(2, "Servos_y:%d  ", Ctrl.Servos_y);
    OLED_DisPlay(1, "uotX:%d    ", (int16_t)Obtain.sPid_X_Out);
    OLED_DisPlay(2, "uotY:%d    ", (int16_t)Obtain.sPid_Y_Out);
}

void Gather_Proc(void)
{
//    Servos_AngleCtl_X(Ctrl.Servos_x);
//    Servos_AngleCtl_Y(Ctrl.Servos_y);
}

void Serial_Proc(void)
{
    if (millis() - uartTick < 20)
        return;          // 如果刷新时间小于20ms就返回
    uartTick = millis(); // 满足条件就刷新当前的tick值

    if (Serial_Index > 0)
    {
        if (Openmv_TraceBall_Split(&getTraceval) == true)   //拆分openmv的数据
        {
//            U1_printf("preX:%d,outX:%d,tarX:%d\r\n", (int16_t)getTraceval.ball_x, (int16_t)Obtain.sPid_X_Out, (int16_t)Servos_Angle_X.target);
            U1_printf("preY:%d,outY:%d,tarY:%d\r\n", (int16_t)getTraceval.ball_y, (int16_t)Obtain.sPid_Y_Out, (int16_t)Servos_Angle_Y.target);
        }
        memset(Serial_Buffer, 0, sizeof(Serial_Buffer));
        Serial_Index = 0;
    }
}

int main(void)
{
    SYS_Init();    // 进行一些系统的初始化，比如系统时钟等
    OLED_Init();   // oled显示
    GPIO_Init();   // 按键端口的初始化
    UART0_Init();  // 接收摄像头数据串口0初始化
    UART1_Init();  // 调试摄像头数据串口1初始化
    ADC_Init();    // ADC获取电源电压
    SERVOS_Init(); // 舵机的初始化
    TIMER0_Init(); // 定时器时基

    U1_printf("this is uart1\r\n");

    Pid_Init(&Servos_Angle_X,NULL,0.1,0,0.5);       //初始化云台的x轴
	Pid_Init(&Servos_Angle_Y,NULL,0.05,0,0.5);      //初始化云台的y轴
	
    while (1)
    {
        Gather_Proc();
        Show_Proc();
        Key_Proc();
        Serial_Proc();
    }
}
